import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, Checkbox, Row, Col, Select, message, Popover, notification } from 'antd';
import AgreementModal from './AgreementModal';
import { checkAccount, register, getCaptchaImage, getSaftCaptchaOp } from './service';
import { getCode } from '@/services/user';
import { UserOutlined, LockOutlined, MailTwoTone } from '@ant-design/icons';
import CommonLoading from '@/components/CommonLoading';
import { mobile, passWord } from '@/utils/rule';
import styles from './index.module.less';

const { Option } = Select;

const Register = () => {
  const navigate = useNavigate();
  const [ form ] = Form.useForm();
  const [ loading, setLoading ] = useState(false);
  const [ visible, setVisible ] = useState(false);
  const [captchaObj, setObj] = useState({});

	const { image: imgCaptcha, key } = captchaObj;

  const onFinish = async val => {
    const { account, password, mobile, smsCode } = val;
    setLoading(true);
    const res = await register({ account, password, mobile, smsCode, tenantId: '000000', appCode: 'ERP', industrialBeltFlag: INDUSTRIAL_BELT_FLAG });
    setLoading(false);
    if(res.success) {
      message.success('注册成功，即将跳转到登录页面');
			navigate('/user/login', {
				state: {
					account: account,
					password: password
				}
			});
    }
  };

  const [ count, setCount ] = useState(0);

  useEffect(()=>{
   if(count){
    setTimeout(()=>{
      setCount(count-1);
    }, 1000)
   }
  },[count])

  useEffect(()=>{
		if(imgCaptcha){
		 form.validateFields(['Captcha-Code'])
		}
	 },[imgCaptcha])

  const prefixSelector = (
    <Form.Item name="prefix"  noStyle>
      <Select style={{ width: 80 }} size='large'>
        <Option value="86">+86</Option>
        <Option value="87">+87</Option>
      </Select>
    </Form.Item>
  );

  const handleGetCode = async (val) => {
    const { data, success } = await getCode({
      mobile: val,
      type: '1',
      industrialBeltFlag: INDUSTRIAL_BELT_FLAG
    })
    if(success){
      if(data){
        message.success('验证码发送成功！');
        setCount(59);
      }else{
        getImgCaptchaFunc(true);
      }
    }
  }

  const getImgCaptchaFunc = async (bool) => {
    const res = await getCaptchaImage();
    if(res?.key && bool){
      notification.info({
        message: `温馨提示`,
        description: '鉴于安全因素，请输入图形验证码，验证通过后方可重新获取手机验证码',
      });   
      setObj(res);
    }
 }

 //获取手机验证码
  const onGetCaptcha = async () => {
    if(imgCaptcha){
      form.validateFields([ 'Captcha-Code', 'mobile' ]).then(val=>{
        getSaftCaptchaFunc(val);
      })
    }else{
      form.validateFields([ 'mobile' ])
      .then(values => {
        // let num = 59;
        // setCount(num);
        // let interval = setInterval(() => {
        //   num = num - 1;
        //   setCount(num);
        //   if(num === 0) {
        //     clearInterval(interval);
        //     setCount(0);
        //   }
        // }, 1000);
        handleGetCode(values.mobile);
      })
    }
  }

  const getSaftCaptchaFunc = async (val) => {
    const { success } = await getSaftCaptchaOp({
      ...val,
      type: '1',
      industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
      'Captcha-Key': key, 
    });
    if(success){
      message.success('验证码发送成功！');
      setCount(59);
      setObj({});
    }else{
      getImgCaptchaFunc();
      form.setFieldsValue({
        'Captcha-Code': null,
        'smsCode': null
      })
    }
 }

  const handleCancel = () => {
    setVisible(false);
  }

  return (
    <>
      <div className={styles.main}>
        <Form
          name='register'
          onFinish={onFinish}
          form={form}
          style={{ width: '100%' }}
          autoComplete='off'
          initialValues={{
            prefix: '86',
          }}
        >
          <Form.Item
            name="account"
            validateTrigger="onBlur"
            validateFirst
            rules={[
              {
                required: true,
                message: '请输入账号',
              },
              {
                max: 18, message: '最多支持18个字符'
              },
              {
                pattern: /^[^\s]*$/,
                message: '不能包含空格',
              },
              {
                pattern: /^([0-9]|[a-z]|[A-Z]){1,}$/,
                message: '只支持英文和数字'
              },
              () => ({
                async validator(rule, value) {
                  if(value) {
                    const { success} = await checkAccount({
                      account: value,
                      tenantId: '000000',
                      industrialBeltFlag: INDUSTRIAL_BELT_FLAG
                    })
                    if (success) {
                      return Promise.resolve();
                    }
                    return Promise.reject('账号名已存在');
                  }
                  return Promise.resolve();
                },
              }),
            ]}
          >
            <Input size="large" prefix={<UserOutlined className={styles.prefixIcon} />} placeholder="请输入账号名,限制18个字符" />
          </Form.Item>
          <Popover  content={
           <div style={{ width: '240px' }}>
             <p style={{ marginBottom: '12px' }}>1、密码至少为8位，且必须包含大小写字母、数字和特殊字符三种</p>
             <p>2、特殊字符支持的有：{`!，@，#，$，%，^，&`}</p>
           </div> 
          } trigger={['click']}  placement="right">
            <Form.Item
              name="password"
              validateFirst
              rules={[
                { required: true, message: '请输入密码' },
                {
                  pattern: /^[^\s]*$/,
                  message: '不能包含空格',
                },
                {
                  pattern: /^[^\u4e00-\u9fa5]{1,}$/g,
                  message: '不支持中文',
                },
                passWord,
              ]}
            >
              <Input
                prefix={<LockOutlined className={styles.prefixIcon} />}
                type="password"
                size="large"
                placeholder="请输入密码"
                autoComplete="new-password" 
              />
            </Form.Item>
          </Popover>
          <Form.Item
            name="confirm"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('两次输入密码不一致');
                },
              }),
            ]}
          >
            <Input
              prefix={<LockOutlined className={styles.prefixIcon} />}
              type="password"
              size="large"
              placeholder="请确认密码"
            />
          </Form.Item>
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              mobile
            ]}
          >
            <Input size='large' addonBefore={prefixSelector} />
          </Form.Item>
          {
            imgCaptcha && <Row gutter={8}>
            <Col span={16}>
              <Form.Item
                name="Captcha-Code"
                rules={[
                  { required: true, message: '请输入验证码' },
                  { pattern: /^[A-Za-z0-9]+$/, message: '输入格式有误' },
                ]}
              >
                <Input size="large" prefix={<MailTwoTone className={styles.prefixIcon} />} placeholder="请输入验证码！"/>
              </Form.Item>
            </Col>
            <Col span={8}>
              <img alt="captcha" src={imgCaptcha} className={styles.getImgCaptcha} onClick={getImgCaptchaFunc} />
            </Col>
          </Row>
          }
          <Row gutter={8}>
            <Col span={16}>
              <Form.Item 
                name="smsCode" 
                rules={[{ required: true, message: '请输入验证码' }]}
              >
                <Input size="large" prefix={<MailTwoTone className={styles.prefixIcon} />} placeholder="请输入验证码！" />
              </Form.Item>
            </Col>
            <Col span={8} style={{ textAlign: 'right' }}>
              <Button disabled={count} style={{ width: '100%', fontSize: '14px', padding: 0 }} onClick={onGetCaptcha} size='large'>{ count ? `${count}s` : '获取验证码'}</Button>
            </Col>
          </Row>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <Form.Item
              name="agreement"
              valuePropName="checked"
              rules={[
                { validator:(_, value) => value ? Promise.resolve() : Promise.reject('阅读并同意用户协议') },
              ]}
            >
              <Checkbox>
                阅读并同意<span className="common-color2" onClick={() => setVisible(true)}>《用户协议》</span>
              </Checkbox>
            </Form.Item>
            <a href="#/user/login">使用已有账号登录</a>
          </div>
          <Form.Item >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Button type='primary' htmlType='submit' size='large' style={{ width: '100%' }}>注册</Button>
            </div>
          </Form.Item>
        </Form>
      </div>
      <AgreementModal visible={visible} handleCancel={handleCancel} />
      <CommonLoading loading={loading} />
    </>
  )
}

export default Register